package com.project.controller;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.project.model.AdviertisementModel;
import com.project.model.CityModel;
import com.project.model.IndustryModel;
import com.project.model.ShopModel;
import com.project.service.AdviertisementService;
import com.project.service.CityService;
import com.project.service.IndustryService;
import com.project.service.ShopService;
import com.project.utils.DistanceUtil;

@RestController
@RequestMapping(value = "index")
public class IndexController {
	
	@Autowired
	private IndustryService industryService;
	
	@Autowired
	private AdviertisementService adviertisementService;
	
	@Autowired
	private CityService cityService;
	
	@Autowired
	private ShopService shopService;
	
	@RequestMapping("")
	public ModelAndView index(HttpServletRequest request) throws FileNotFoundException, ScriptException {
		ModelAndView view = new ModelAndView();
		String lng = "116.331398";
		String lat = "39.897445";
		String location = "";
		
		if (null != request.getParameter("city") && !"".equals(request.getParameter("city").trim())) {
			location = request.getParameter("city");
		} else if (null != request.getSession().getAttribute("location") && !"".equals(request.getSession().getAttribute("location"))) {
			location = request.getSession().getAttribute("location").toString();
		}
		
		if (null != location && !"".equals(location)) {
			view.addObject("location", location);
			
			if (null != request.getSession().getAttribute("lng") && !"".equals(request.getSession().getAttribute("lng"))) {
				lng = request.getSession().getAttribute("lng").toString();
			}
			
			if (null != request.getSession().getAttribute("lat") && !"".equals(request.getSession().getAttribute("lat"))) {
				lat = request.getSession().getAttribute("lat").toString();
			}
			
			// 获取推荐分类
			List<IndustryModel> industrys =  industryService.getIndustryModelByIsHot(1);
			view.addObject("industrys", industrys);
			
			// 获取广告
			List<AdviertisementModel> adviertisements =  adviertisementService.listAdviertisementModelAll();
			view.addObject("adviertisements", adviertisements);
			
			// 根据城市名称获取城市CODE
			List<CityModel> citys = cityService.getCityCodeByName(location);
			
			// 根据城市CODE获取推荐店铺
			ShopModel recommend_shop = new ShopModel();
			if (null == citys || citys.size() == 0) {
				citys = cityService.getCityCodeByName("北京市");
			}
			
			if (citys.get(0).getType() == 1) {
				recommend_shop.setProvince(citys.get(0).getCode());
			} else if (citys.get(0).getType() == 2) {
				recommend_shop.setCity(citys.get(0).getCode());
			} else if (citys.get(0).getType() == 3) {
				recommend_shop.setArea(citys.get(0).getCode());
			}
			List<ShopModel> recommend_shops = shopService.getListByIndexAndCondition(recommend_shop);
			view.addObject("recommend_shops", recommend_shops);
			
			// 根据经纬度获取附近店铺
			/*Map<String, Object> condition = DistanceUtil.getAround(lat, lng, "50000");
			condition.put("size", 15);
			List<ShopModel> condition_shopModels = shopService.getListByIndexAndDistance(condition);
			*/
			List<ShopModel> condition_shopModels = getShopList(citys.get(0).getCode(), "", "", 0, 0, lat, lng, 1);
			if (null != condition_shopModels && condition_shopModels.size() > 0) {
				for (int i=0; i<condition_shopModels.size(); i++) {
					String distance_str = DistanceUtil.getDistance(lat, lng, condition_shopModels.get(i).getLatitude(), condition_shopModels.get(i).getLongitude());
					int distance = Integer.parseInt(distance_str);
					if (distance > 1000) {
						 java.text.DecimalFormat df = new java.text.DecimalFormat("#");
						distance_str = df.format(distance/1000) + "km";
					} else {
						distance_str = distance_str + "m";
					}
					condition_shopModels.get(i).setDistance(distance_str);
				}
			}
			view.addObject("condition_shops", condition_shopModels);
			
			view.setViewName("index.jsp");
		} else {
			view.setViewName("my_location.jsp");
		}
		return view;
	}
	
	@RequestMapping("/location")
	public @ResponseBody Map<String, String> location(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		String location = request.getParameter("l");
		String lng = request.getParameter("lng");
		String lat = request.getParameter("lat");
		String street_info = request.getParameter("street_info");
		if ((null != location && !location.equals("")) && (null != lng && !lng.equals("")) && (null != lat && !lat.equals(""))) {
			request.getSession().setAttribute("location", location);
			request.getSession().setAttribute("lng", lng);
			request.getSession().setAttribute("lat", lat);
			request.getSession().setAttribute("street_info", street_info);
		} else {
			request.getSession().setAttribute("location", "北京市");
			request.getSession().setAttribute("lng", "116.331398");
			request.getSession().setAttribute("lat", "39.897445");
		}
		map.put("code", "0");
		return map;
	}
	
	private List<ShopModel> getShopList(String city, String area, String street, int industry, int industry_small, String lat, String lng, int sort) {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("size", 6);
		if (null != city && !"".equals(city)) {
			condition.put("city", city);
		}
		if (null != area && !"".equals(area)) {
			condition.put("area", area);
		}
		if (null != street && !"".equals(street)) {
			condition.put("street", street);
		}
		if (industry > 0) {
			condition.put("p_industry", industry);
		}
		if (industry_small > 0) {
			condition.put("industry", industry_small);
		}
		// 获取店铺列表
		List<ShopModel> condition_shopModels = shopService.getShopModelByCondition(condition);
		if (null != condition_shopModels && condition_shopModels.size() > 0) {
			for (int i=0; i<condition_shopModels.size(); i++) {
				String distance_str = DistanceUtil.getDistance(lat, lng, condition_shopModels.get(i).getLatitude(), condition_shopModels.get(i).getLongitude());
				int distance = Integer.parseInt(distance_str);
				if (distance > 1000) {
					 java.text.DecimalFormat df = new java.text.DecimalFormat("#");
					distance_str = df.format(distance/1000) + "km";
				} else {
					distance_str = distance_str+"m";
				}
				condition_shopModels.get(i).setDistance(distance_str);
			}
			if (sort == 2) {
				// 按点击数倒序  
		        Collections.sort(condition_shopModels, new Comparator<ShopModel>() {
		            public int compare(ShopModel arg0, ShopModel arg1) {
		                double hits0 = Double.parseDouble(arg0.getDistance().replace("km", "").replace("m", ""));
		                double hits1 = Double.parseDouble(arg1.getDistance().replace("km", "").replace("m", ""));
		                if (hits1 > hits0) {
		                    return 1;
		                } else if (hits1 == hits0) {
		                    return 0;
		                } else {
		                    return -1;
		                }
		            }
		        });
			} else if (sort == 3) {
				
			} else if (sort == 4) {
				Collections.sort(condition_shopModels, new Comparator<ShopModel>() {
		            public int compare(ShopModel arg0, ShopModel arg1) {
		                Date hits0 = arg0.getCreateTime();
		                Date hits1 = arg1.getCreateTime();
		                if (hits1.before(hits0)) {
		                    return 1;
		                } else if (hits1 == hits0) {
		                    return 0;
		                } else {
		                    return -1;
		                }
		            }
		        });
			}
		} else {
			condition_shopModels = new ArrayList<ShopModel>();
		}
		
		return condition_shopModels;
	}
}